﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;

namespace TouchControls
{    
    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class TouchScrollViewer : ScrollViewer
    {
        private bool _manipulationCanceled;
        protected override void OnManipulationInertiaStarting(System.Windows.Input.ManipulationInertiaStartingEventArgs e)
        {
            if (_manipulationCanceled) return;
            
            base.OnManipulationInertiaStarting(e);            
        }

        protected override void OnManipulationStarting(System.Windows.Input.ManipulationStartingEventArgs e)
        {
            _manipulationCanceled = false;
            base.OnManipulationStarting(e);
            e.Handled = false;
        }

        protected override void OnManipulationBoundaryFeedback(System.Windows.Input.ManipulationBoundaryFeedbackEventArgs e)
        {
            base.OnManipulationBoundaryFeedback(e);
            e.Handled = false;
        }

        protected override void OnManipulationStarted(System.Windows.Input.ManipulationStartedEventArgs e)
        {
            base.OnManipulationStarted(e);
            e.Handled = false;
            _manipulationCanceled = false;
        }

        protected override void OnManipulationDelta(System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            if (_manipulationCanceled)
            {
                return;
            }

            if (VerticalScrollBarVisibility != ScrollBarVisibility.Disabled && HorizontalScrollBarVisibility != ScrollBarVisibility.Disabled)
            {
                base.OnManipulationDelta(e);
                return;
            }

            var absX = Math.Abs(e.CumulativeManipulation.Translation.X);
            var absY = Math.Abs(e.CumulativeManipulation.Translation.Y);

            if (VerticalScrollBarVisibility != ScrollBarVisibility.Disabled)
            {
                if (absY > absX)
                {
                    base.OnManipulationDelta(e);
                    return;
                }
            }
            if (HorizontalScrollBarVisibility != ScrollBarVisibility.Disabled)
            {
                if (absX > absY)
                {
                    base.OnManipulationDelta(e);
                    return;
                }
            }
            
            _manipulationCanceled = true;
        }

        protected override void OnManipulationCompleted(System.Windows.Input.ManipulationCompletedEventArgs e)
        {
            if (_manipulationCanceled) return;

            base.OnManipulationCompleted(e);
        }
    }
}
